#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int j = 0;
double H = 0;
double sum = 0;
double p[100] = {0};
void fenshu();
void xiaoshu();

struct FenShu
{
    int n;
    char a;
    int m;
};
struct FenShu f[100];

int main()
{
    int i, a;
    double k;
    double n, m;
    printf("	请选择输入数值的方式:\n	1.分数形式:\n	2.小数形式:\n");
    printf("	请选择:		");
    scanf("%d", &a);
    switch (a)
    {
    case 1:
        fenshu();
        break;
    case 2:
        xiaoshu();
        break;
    default:
        printf("\n	输入错误，按任意键退出！\n\n");
        exit(0);
    }
    for (i = 0; i < j; i++)
        sum += p[i];
    printf("	离散信源概率和 =  %lf\n\n", sum);
    printf("H(x):");
    for (i = 0; i < j; i++)
    {
        H = H + (double)(p[i] * (log2((double)1 / p[i])));
        printf("	%lf", H);
    }
    printf("\n\n	一维离散信源熵:	H(x) = %lf\n\n\n\n", H);
    return 0;
}

void fenshu()
{
    int i, a;
    double k;
    double n, m;
    printf("	请输入要计算的离散信源概率:	");
    for (i = 0;; i++)
    {
        scanf("%d%c%d", &f[i].n, &f[i].a, &f[i].m);
        if (getchar() == '\n')
            break;
    }
    printf("\n");
    j = i + 1;
    for (i = 0; i < j; i++)
    {
        n = (double)(f[i].n);
        m = (double)(f[i].m);
        k = n / m;
        if (f[0].a == '/')
            p[i] = k;
    }
    printf("P(x):");
    for (i = 0; i < j; i++)
    {
        printf("	%d%c%d", f[i].n, f[i].a, f[i].m);
    }
    printf("\n\n");
}

void xiaoshu()
{
    int i;
    printf("	请输入要计算的离散信源概率:	");
    for (i = 0;; i++)
    {
        scanf("%lf", &p[i]);
        if (getchar() == '\n')
            break;
    }
    j = i + 1;
    printf("\n");
    printf("P(x):");
    for (i = 0; i < j; i++)
    {
        printf("	%lf    ", p[i]);
    }
    printf("\n\n");
}
